
#include <sys/socket.h>
#include <sys/types.h>
#include <iostream>
#include <string>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include "Log.hpp"
#include "Protocol.hpp"
using namespace MyLogModule;
using namespace std;
int main(int argc,char* argv[])
{
    if(argc != 3)
    {
        cout << "User: TcpClient ip_address port" << endl;
        return 1;
    }
    //1. 创建socket
    int socket = ::socket(AF_INET,SOCK_STREAM,0);
    if(socket < 0)
    {
        cout << "socket fail " << endl;
        return 2;
    }
    //2. 设置
    string server_ip = argv[1];
    int server_port = stoi(argv[2]);

    struct sockaddr_in server_addr;
    memset(&server_addr,0,sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(server_port);
    server_addr.sin_addr.s_addr = inet_addr(server_ip.c_str());

    int n = ::connect(socket,(sockaddr*)&server_addr,sizeof(server_addr));
    if(n < 0)
    {
        cout << "connect fail" << endl;
        return 3;
    }
    cout << "connect success,n:" << n << endl;

    while(true)
    {
        int x, y;
        char oper;
        std::cout << "input x: ";
        std::cin >> x;
        std::cout << "input y: ";
        std::cin >> y;
        std::cout << "input oper: ";
        std::cin >> oper;
        Request req(x,y,oper);
        //1. 序列化
        string message;
        req.Serialize(message);
        //2. 添加长度报头
        Encode(message);
        //3. 发送信息
        int n = send(socket,message.c_str(),message.size(),0);
        if(n > 0)
        {
            char buffer[1024];
            n = recv(socket,buffer,sizeof(buffer) - 1,0);
            if(n > 0)
            {
                buffer[n] = 0;
                string package = buffer;
                string content;
                //判断是否完整
                if(Decode(package,&content))
                {
                    //反序列化
                    Response res;
                    res.DeSerialize(content);

                    //得到结构化的结果
                    cout << res.GetResult() << " ["<<res.GetCode() <<"]" << endl;
                }
            }
            else
                break;
        }
        else
            break;
    }
    close(socket);
    return 0;
}